class Incident < ActiveRecord::Base
  belongs_to :machine #Permet de créer les associations multiples entre les objets
  belongs_to :regle #Permet de créer les associations multiples entre les objets
  
  validates_presence_of :typeincident
  validates_presence_of :machineid, :regleid

  def self.getstat()

    nb_incidents_an =Incident.find_by_sql("SELECT count( id ) AS Nombre_incidents, year( datedetection ) AS Annee FROM incidents GROUP BY YEAR( datedetection ) ORDER BY Nombre_incidents")

    nb_incidents_mois=Incident.find_by_sql("SELECT count( id ) AS Nombre_incidents, MONTHNAME( datedetection ) AS Mois FROM incidents WHERE year( datedetection ) = year( curdate( ) ) GROUP BY MONTHNAME( datedetection ) ORDER BY Nombre_incidents")
    
    nb_incidents_mois_actuel_regles = Incident.find_by_sql("SELECT count( incidents.id ) AS Nombre_incidents, regles.descregle AS Nom_regle FROM incidents INNER JOIN regles ON regles.id = incidents.regleid WHERE month(datedetection) = month(now())and year( datedetection ) = year( curdate( ) ) GROUP BY regles.descregle ORDER BY Nombre_incidents")

    nb_incidents_mois_actuel_salles = Incident.find_by_sql("SELECT count( incidents.id ) AS Nombre_incidents, salles.nomsalle AS Nom_salle FROM incidents INNER JOIN machines ON machines.id = incidents.machineid INNER JOIN salles ON salles.id = machines.salleid WHERE month(datedetection) = month(now())and year( datedetection ) = year( curdate( ) ) GROUP BY salles.nomsalle ORDER BY Nombre_incidents")

    tab_annee_lib = []
    for liba in nb_incidents_an do
      tab_annee_lib << liba.Annee
    end

    tab_annee_val = []
    for vala in nb_incidents_an do
      tab_annee_val << vala.Nombre_incidents.to_i

    end

    tab_mois_lib = []
    for libm in nb_incidents_mois do
      tab_mois_lib << libm.Mois

    end

    tab_mois_val = []
    for valm in nb_incidents_mois do
      tab_mois_val << valm.Nombre_incidents.to_i

    end

    tab_mois_now_regle_lib = []
    for libmr in nb_incidents_mois_actuel_regles do
      tab_mois_now_regle_lib << libmr.Nom_regle

    end

    tab_mois_now_regle_val = []
    for valmr in nb_incidents_mois_actuel_regles do
      tab_mois_now_regle_val << valmr.Nombre_incidents.to_i

    end

    tab_mois_now_salle_lib = []
    for libms in nb_incidents_mois_actuel_salles do
      tab_mois_now_salle_lib << libms.Nom_salle

    end

    tab_mois_now_salle_val = []
    for valms in nb_incidents_mois_actuel_salles do
      tab_mois_now_salle_val << valms.Nombre_incidents.to_i

    end
    
    return tab_annee_lib, tab_annee_val, tab_mois_lib, tab_mois_val, tab_mois_now_regle_lib, tab_mois_now_regle_val, tab_mois_now_salle_lib, tab_mois_now_salle_val
  end

  def self.agent(mapage, espace, ram, cpu, monagent, leping)
    if mapage.nil?
      tab_inci = nil
      agent_random = rand(Machine.find(:all, :conditions => "salleid is not null").count)
      machines = Machine.find(:all, :conditions => "salleid is not null AND id = #{agent_random + 1}")
      
      for machine in machines do

        #On verifie l'etat du reseau
        ping = rand(100)
        if ping >= 10
          #Si le reseau est OK, on vérifie l'état de l'agent
          agent = rand(100)
          if agent >= 10
            probleme = rand(100)
            if probleme <= 10
              memoiretotal = rand(100)
              ope_memoire = Regle.find(:first, :conditions => "descregle ='ram_utilise'")
              ope_espace = Regle.find(:first, :conditions => "descregle ='cpu_utilise'")

              if (memoiretotal.to_s + "% " + ope_memoire.operationarithme + " " + ope_memoire.valeurlimite)
                incident = Incident.find(:first, :conditions => "regleid = #{ope_memoire.id} AND machineid = #{machine.id}")

                tab_inci = {:machineid => machine.id, :typeincident => ope_memoire.descregle, :datedetection => Time.now.strftime('%Y-%m-%d'), :etat => "a traiter", :regleid => ope_memoire.id}
              end
            end
          else
            regleid = Regle.find(:first, :conditions => "descregle = 'agent_operationnel'").id
            incident = Incident.find(:first, :joins => "INNER JOIN regles ON regles.id=incidents.regleid", :conditions => "descregle = 'agent_operationnel' AND machineid = #{machine.id} AND etat in ('a traiter','en cours')")
            if !incident.nil?
              tab_inci = {:machineid => machine.id, :typeincident => 'agent_operationnel', :datedetection => Time.now.strftime('%Y-%m-%d'), :etat => "a traiter", :regleid => regleid}
            end
          end
        else

          regleid = Regle.find(:first, :conditions => "descregle = 'etat_reseau'").id
          incident = Incident.find(:first, :joins => "INNER JOIN regles ON regles.id=incidents.regleid", :conditions => "descregle = 'etat_reseau' AND machineid = #{machine.id} AND etat in ('a traiter','en cours')")
          tab_inci = {:machineid => machine.id, :typeincident => 'etat_reseau', :datedetection => Time.now.strftime('%Y-%m-%d'), :etat => "a traiter", :regleid => regleid}
        end
      end

    elsif mapage.eql?("machine")
      tab_inci = []
      params_inci = []
      #On verifie l'etat du reseau
        ping = rand(100)
        if ping >= 10
          tab_inci += ["Ping OK"] if !leping.nil?
          
          #Si le reseau est OK, on vérifie l'état de l'agent
          agent = rand(100)
          
          if agent >= 10
            tab_inci += ["Agent OK"] if !monagent.nil?
            
            
              if !espace.nil?
                regespace = rand(100).to_s + "%"
                regles = Regle.find(:first, :conditions => "id = #{espace}")
                if regespace + regles.operationarithme + " " + regles.valeurlimite
                  tab_inci += ["Erreur - d'espace mémoire de la machine #{regles.operationarithme} #{regles.valeurlimite}"]
                  params_inci += [espace]
                else
                  tab_inci += ["Espace mémoire OK"]
                end
              end

              if !ram.nil?
                regram = rand(100).to_s + "%"
                regles = Regle.find(:first, :conditions => "id = #{ram}")
                
                if regram + regles.operationarithme + " " + regles.valeurlimite
                  tab_inci += ["Erreur - ram utilisée de la machine #{regles.operationarithme} #{regles.valeurlimite}"]
                  params_inci += [ram]
                else
                  tab_inci += ["Ram OK"]
                end
              end

              if !cpu.nil?
                regcpu = rand(100).to_s + "%"
                regles = Regle.find(:first, :conditions => "id = #{cpu}")
                if regcpu + regles.operationarithme + " " + regles.valeurlimite
                  tab_inci += ["Erreur - CPU de la machine #{regles.operationarithme} #{regles.valeurlimite}"]
                  params_inci += [cpu]
                else
                  tab_inci += ["CPU OK"]
                end
              end
          else
             
              tab_inci += ["Erreur - L'agent installé sur le poste est injoignable."]
              params_inci += [monagent]
          end
        else
          tab_inci += ["Erreur - Machine injoignable. Ping échoué."]
          params_inci += [leping]
        end
    end
    
    return tab_inci, params_inci
  end

  def self.getmachine()
    liste_machine = Incident.find_by_sql("SELECT * FROM machines INNER JOIN  incidents  on machines.id = incidents.machineid")
    return liste_machine
  end
    def self.getsalle()
    liste_salle = Incident.find_by_sql("SELECT id, nomsalle FROM  salles order by nomsalle")
    return liste_salle
  end
end
